package com.lxz.usercenter.job;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxz.usercenter.model.domain.User;
import com.lxz.usercenter.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 缓存预热
 */
@Component
@Slf4j
public class preCacheJob {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserService userService;
    @Resource
    private RedissonClient redissonClient;

    //白名单，重点缓存用户
    private List<Long> whiteList = Arrays.asList(1L, 2L, 3L, 4L, 5L, 7L, 8L, 9L, 10L);

    //定时任务，每天晚上23:59执行一次
    @Scheduled(cron = "0 59 23 * * *")
    public void doCacheRecommendUser() {
        RLock rLock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            //只有一个线程可以获取到锁
            if (rLock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("获取到锁:" + Thread.currentThread().getId());
                ValueOperations<String, Object> ValueOperations = redisTemplate.opsForValue();
                for (Long userId : whiteList) {
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    List<User> userList = userService.list(queryWrapper);
                    List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
                    //存入缓存
                    try {
                        ValueOperations.set(redisKey, list, 10, TimeUnit.MINUTES);
                    } catch (Exception e) {
                        log.error("redis存储异常", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("获取锁异常", e);
        } finally {
            //只能释放自己的锁
            if (rLock.isHeldByCurrentThread()) {
                rLock.unlock();
                System.out.println("释放锁:" + Thread.currentThread().getId());
            }
        }

    }
}
